<template>
  <el-container>
    <el-main>
      <el-form ref="orderForm" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">销售单</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="5">
            <el-form-item label="调出门店">
              <el-select style="width: 100%" v-model="outName"  value-key="id" :filter-method="remoteMethod" @change="changeShop" placeholder="请选择门店" >
                <el-option v-for="item in shops" :label="item.name" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售日期"  prop="orderDate">
              <el-date-picker
                style="width: 100%"
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="5">
            <el-form-item label="调入门店">
              <el-select style="width:100%"  v-model="form.inShopId" :filter-method="remoteMethod" placeholder="请选择门店">
                <el-option v-for="item in shops" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="仓管人员">
              <el-select style="width: 100%" v-model="operatorName" filterable placeholder="请选择"
                         @change="selectSysEmployee">
                <el-option
                  v-for="item in sysEmployeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--<el-col :span="5">-->
            <!--<el-form-item label="所属部门">-->
              <!--<el-input v-model="officeName" suffix-icon="el-icon-arrow-down" @focus="dialogShow"/>-->
            <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="10">
            <el-form-item label="留言">
              <el-input v-model="form.memo"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
          <div style="display: flex;padding-top: 10px;padding-bottom: 10px">
            <el-input v-model="query.sn" placeholder="请输入货号" @change="queryClick"></el-input>
<!--            <el-button style="margin-left: 20px;margin-right: 10px" type="primary" icon="el-icon-plus"-->
<!--                       @click="moreProductClick">批量录入-->
<!--            </el-button>-->
          </div>
        </div>
        <!--商品规格-->
        <el-table
          :data="productList"
          border
          show-summary
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名"
         >
            <template slot-scope="{row}">
              <div style="position: relative">
                <i class="el-icon-arrow-down" style="position: absolute;bottom: 11px;color: #CCCC;right: 8px;z-index: 99;"></i>
                <el-select style="width: 100%" v-model="row.name" filterable placeholder="请选择" remote :remote-method="productMethod" @change="selectClick" @focus="tableClick(row)">
                  <el-option
                    v-for="(item,index) in listForm"
                    :key="index"
                    :label="item.name"
                    style="width:650px"
                    :value="index"
                  >
                    <div style="display: flex">
                      <span style="width: 80px;overflow: hidden;text-overflow: ellipsis;">{{ item.sn }}</span>
                      <span style="float: left;width: 160px;overflow: hidden;text-overflow: ellipsis;margin-left: 10px">{{ item.name }}</span>
                      <div style="width: 200px;">
                        <span style="color: #8492a6; font-size: 8px;">{{item.spec1}}</span>
                      </div>
                    </div>
                  </el-option>
                  <div style="display: flex;width: 100%;position: absolute;bottom: 0">

                    <div style="width: 50%;background-color: rgb(248,248,248);"></div>
                    <div class="elOption" @click="toAddProduct">搜索商品</div>
                    <div class="elOption1" @click="toSearchProduct">新增商品</div>
                  </div>
                  <div style="height: 30px"></div>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="150"
          >
            <template slot-scope="{row}">
              <span>{{row.sn}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            max-width="300"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.spec}}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="单位"
            width="50"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            align="center"
            width="70">
            <template slot-scope="{row}">
              <el-input @change="refreshClick" v-model="row.quantity"/>
            </template>
          </el-table-column>
          <el-table-column
            label="调拨价"
            width="70"
            prop="price">
          </el-table-column>
          <!--<el-table-column-->
            <!--label="出库数量"-->
            <!--width="70"-->
            <!--align="right"-->
            <!--prop="shippedQuantity"-->
          <!--&gt;-->
          <!--</el-table-column>-->
          <!--<el-table-column-->
            <!--label="入库数量"-->
            <!--width="70"-->
            <!--align="right"-->
            <!--prop="receiviedQuantity"-->
          <!--&gt;-->
          <!--</el-table-column>-->
          <el-table-column
            align="center"
            width="70"
            label="操作"
          >
            <template slot-scope="{row}">
              <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                <a @click="delProduct(row)">
                  <i style="color: #F56C6C" class="el-icon-delete"></i>
                </a>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
<!--        <el-button type="primary" style="margin-top: 20px" @click="addProduct">添加规格</el-button>-->
        <div style="display: flex;justify-content: flex-end">
<!--          <el-button type="primary" style="margin-top: 20px" v-permission="['allocate.out']" :loading="clicked" @click="editAlloteOut('orderForm')">保存并出库</el-button>-->
<!--          <el-button type="success" style="margin-top: 20px" v-permission="['allocate.audit']" :loading="clicked" @click="editConfirm('orderForm')">保存并确认</el-button>-->
          <el-button  style="margin-top: 20px" :loading="clicked" @click="editClick('orderForm')">保存</el-button>
        </div>

      </el-form>
      <el-dialog
        title="新增商品"
        :visible.sync="procuctVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="productClose">
        <div style="height: 65vh;overflow: auto;position: relative;">
          <productAdd :type="productType" @saveProduct="saveProduct"></productAdd>
        </div>
      </el-dialog>
      <el-dialog
        title="添加商品"
        :visible.sync="orderVisible"
        width="950px"
        v-el-drag-dialog
        :before-close="orderClose">
        <div style="position: relative;">
          <productTable ref="productList" @orderClose="orderClose" @doubleClick="doubleClick" @addClick="addClick"></productTable>
        </div>
      </el-dialog>
      <el-dialog
        title="选择商品"
        :visible.sync="queryType"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="queryClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <productRadio :findByList="findByList" @findByClick="findByClick"></productRadio>
        </div>
      </el-dialog>
      <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
    </el-main>
  </el-container>
</template>
<script>
  import {EventBus} from '@/api/eventBus'
  import {list as productList} from '@/api/product'
  import {list as sysEmployeeList} from '@/api/sysEmployee'
  import {update} from '@/api/allocate'
  import {find,updateAndConfirm,updateAndAlloteOut} from '../../api/allocate'
  import utils from '../../utils/utils.js'
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from '../../components/ProductList/productList'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import OfficeDialog from '@/components/OfficeDialog'
  import {findBySn} from "../../api/product";
  import productRadio from './components/productRadio'
  import {list as shopList} from '../../api/shop'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  export default {
    directives: {elDragDialog,permission},
    name: 'allocate-edit',
    data() {
      return {
        clicked: false, // 按钮防双击
        shops:[],
        outName:'',
        form: {
          outShopId:'',
          inShopId:'',
          id: '',
          memberId: '',
          orderDate: new Date(),
          operatorId: '',
          // property: 0,
          orderMethod:0,
          shippingMethod: '',
          officeId: '',
          areaId: 440000,
          areaName: '广东省广州市海珠区',
          address: '',
          memo: '',
          consignee:'',
          phone:'',
          freight: 0,
          amountPayable: 0,
          amountPaid: 0,
          subPrice: 0,
          subQuantity: 0,
          offsetAmount:0,
        },
        productList: [],
        query: {
          sn: ''
        },
        keyword: {
          sn: ''
        },
        listForm: [],
        tableIndex: '',
        procuctVisible: false,
        orderVisible: false,
        productType: 'order',
        chooseOrderName: '',
        district: {province: 440000, city: '广州市', area: '海珠区'},
        memberName: '',
        memberType: 'add',
        sysEmployeeList: [],
        operatorName: '',
        officeName: '',
        rules: {
          outShopId: [
            {required:true, message: '请选择调出门店', trigger: 'change'},
          ],
          inShopId: [
            {required: true, message: '请选择调入门店', trigger: 'change'}
          ],
          createDate: [
            {required: true, message: '请选择日期', trigger: 'change'}
          ],
        },
        queryType:false,
        findByList:[],
        memberId:'',
        // type:''
      }
    },
    created() {
      var _this = this;
      _this.form.id = this.$route.query.id;
      find(this.$route.query.id).then(response => {
        _this.form.id = response.data.allocate.id
        _this.form.inShopId=response.data.allocate.inShopId
        _this.form.operatorId=response.data.allocate.operatorId
        _this.operatorName=response.data.allocate.operatorName
        _this.form.outShopId=response.data.allocate.outShopId
        _this.outName=response.data.allocate.outShopName
        _this.form.officeId = response.data.allocate.officeId;
        _this.officeName = response.data.officeName;
        _this.form.memo = response.data.allocate.memo;
        _this.productList = response.data.allocate.itemList
        _this.addProduct()
        _this.form.orderDate=response.data.allocate.orderDate
      }).catch(error => {
      })
      this.loadlist('');
      this.loadShop('')
      this.loadSysEmployee()
    },
    components: {
      productAdd, productTable, Distpicker, OfficeDialog ,productRadio,
    },
    methods: {
      remoteMethod(query){
        this.loadShop(query)
      },
      changeShop(data){
          if (this.form.outShopId!=data.id){
            this.productList=[]
            this.outName=data.name
            this.form.outShopId=data.id
          }
          this.addProduct()
      },
      toAddProduct(){
        this.orderVisible = true;

      },
      toSearchProduct(){
        this.procuctVisible = true;
      },
      loadShop(query){
        let params=new URLSearchParams()
        params.append('name',query)
        shopList(params).then(res=>{
          this.shops=res.data.data
        })
      },
      productMethod(query){
        this.loadlist(query)
      },
      //删除商品列表
      delProduct(row) {
        var index = this.productList.indexOf(row)
        if (index !== -1) {
          this.productList.splice(index, 1)
        }
        this.addProduct()
      },
      //新增商品
      addProduct() {

        var _this = this
        if (_this.productList.length == 0) {
          _this.productList.push({
            productId: '',
            name: '',
            sn: '',
            price: '',
            orders: '',
            quantity: '',
            subTotal: '',
            amountPaid: 0,
            spec: '',
            discount: 0,
            cost: 0,
            unit: ''
          })
        } else {
          if (_this.productList[_this.productList.length - 1].productId!= '') {
            _this.productList.push({
              productId: '',
              name: '',
              sn: '',
              price: '',
              orders: '',
              quantity: '',
              subTotal: '',
              amountPaid: 0,
              spec: '',
              discount: 0,
              cost: 0,
              unit: ''
            })
          }
        }
      },
      //商品总数据
      loadSysEmployee() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageSize',100)
        sysEmployeeList(params).then(response => {
          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      loadlist(query) {
        var _this = this
        let params = new URLSearchParams();
        params.append('keyword',query)
        params.append('sn', _this.keyword.sn)
        productList(params).then(response => {
          console.log(response);
          _this.listForm = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },
      //更多商品弹出
      moreProductClick() {
        var _this = this;
        _this.orderVisible = true;
      },
      doubleClick(data) {
        var goodsDetails = {
          productId: data.id,
          name: data.name,
          sn: data.sn,
          price: data.price,
          orders: data.orders,
          subTotal: data.price,
          // cost: item.cost,
          amountPaid: 0,
          discount: 0,
          quantity: 1,
          spec: data.spec1 ,
          unit: data.unit
        }
        this.productList.push(goodsDetails)
        this.procuctFilter();
        this.addProduct()

      },
      addClick(data) {
        var _this = this
        data.forEach(item=>{
          var goodsDetails = {
            productId: item.id,
            name: item.name,
            sn: item.sn,
            price: item.price,
            orders: item.orders,
            subTotal: item.price,
            // cost: item.cost,
            amountPaid: 0,
            discount: 0,
            quantity: 1,
            spec: item.spec1 ,
            unit: item.unit
          };
          _this.productList.push(goodsDetails)
        })
        this.procuctFilter();
        _this.addProduct()
      },
      orderClose() {
        this.orderVisible = false;
        if ( this.productList.length>0&&this.chooseOrderName!=''){
          this.productList[this.tableIndex].name = this.chooseOrderName
        }
        this.$refs.productList.cancelClick();
      },
      //商品表下拉选择
      selectClick(index) {
        var _this = this
        if (index == '#') {
          _this.procuctVisible = true;
        } else if(index=='/'){
          this.orderVisible = true;
        } else {
          console.log(_this.listForm[index])
          var goodsDetails = {
            productId: _this.listForm[index].id,
            name: _this.listForm[index].name,
            sn: _this.listForm[index].sn,
            cost: _this.listForm[index].cost,
            price: _this.listForm[index].price,
            orders: _this.listForm[index].orders,
            subTotal: _this.listForm[index].price,
            unit:_this.listForm[index].unit,
            spec: _this.listForm[index].spec1 + _this.listForm[index].spec2,
            amountPaid: 0,
            discount: 0,
            quantity: 1
          };
          _this.productList[_this.tableIndex] = goodsDetails
        }
        this.procuctFilter()
        this.addProduct()
      },
      //获取当前点击商品表行
      tableClick(data) {
        this.tableIndex = this.productList.indexOf(data);
        this.chooseOrderName = this.productList[this.tableIndex].name
      },
      //新增商品弹窗
      productClose() {
        this.procuctVisible = false;
        this.productList[this.tableIndex].name = this.chooseOrderName
      },
      saveProduct(data) {
        this.listForm.splice(0, 0, data);
        this.productList[this.tableIndex] = data;
        this.procuctVisible = false;
      },
      //商品过滤
      procuctFilter() {
        let newfood = [];
        var temp = {};
        for (var i in this.productList) {
          if (this.productList[i].productId != '') {
            var key = this.productList[i].productId;
            if (temp[key]) {
              temp[key].productId = temp[key].productId;
              temp[key].quantity = temp[key].quantity + this.productList[i].quantity;
              temp[key].subTotal = (parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity)).toFixed(2);
              temp[key].amountPaid = temp[key].subTotal
            } else {
              temp[key] = {};
              temp[key].productId = this.productList[i].productId;
              temp[key].quantity = this.productList[i].quantity;
              temp[key].subTotal = (parseFloat(this.productList[i].price) * parseFloat(temp[key].quantity)).toFixed(2);
              temp[key].amountPaid = temp[key].subTotal
            }
            temp[key].name = this.productList[i].name;
            temp[key].sn = this.productList[i].sn;
            temp[key].price = this.productList[i].price;
            temp[key].cost = this.productList[i].cost;
            temp[key].orders = this.productList[i].orders;
            temp[key].discount = this.productList[i].discount;
            temp[key].spec = this.productList[i].spec;
            temp[key].unit = this.productList[i].unit
          }
        }
        for (var k in temp) {
          newfood.push(temp[k])
        }
        this.productList = newfood
        console.log(newfood)
      },
      editConfirm(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            if (_this.productList[_this.productList.length-1].productId==''){
              _this.productList.splice(_this.productList.length-1,1)
            }
            _this.productList.forEach(function (item) {
              var goodsDetails = {
                id:item.id,
                allocateId:item.allocateId,
                productId: item.productId,
                name: item.name,
                sn: item.sn,
                price: item.price,
                quantity: item.quantity,
                spec: item.spec,
                cost: item.cost,
                unit:item.unit
              };
              itemList.push(goodsDetails)
            });
            let formData = {
              id:_this.form.id,
              orderDate: _this.form.orderDate,
              outShopId:this.form.outShopId,
              inShopId:this.form.inShopId,
              officeId: _this.form.officeId,
              memo: _this.form.memo,
              itemList: itemList
            };
            updateAndConfirm(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('allocate-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/allocate/view', query: {id: _this.form.id}
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      editAlloteOut(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            if (_this.productList[_this.productList.length-1].productId==''){
              _this.productList.splice(_this.productList.length-1,1)
            }
            _this.productList.forEach(function (item) {
              var goodsDetails = {
                id:item.id,
                allocateId:item.allocateId,
                productId: item.productId,
                name: item.name,
                sn: item.sn,
                price: item.price,
                quantity: item.quantity,
                spec: item.spec,
                cost: item.cost,
                unit:item.unit
              };
              itemList.push(goodsDetails)
            });
            let formData = {
              id:_this.form.id,
              orderDate: _this.form.orderDate,
              outShopId:this.form.outShopId,
              inShopId:this.form.inShopId,
              officeId: _this.form.officeId,
              memo: _this.form.memo,
              itemList: itemList
            };
            updateAndAlloteOut(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('allocate-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/allocate/view', query: {id: _this.form.id}
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      //订单保存
      editClick(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            let itemList = [];
            _this.productList.forEach(function (item) {
              if (item.productId != ''){
                var goodsDetails = {
                  id:item.id,
                  allocateId:item.allocateId,
                  productId: item.productId,
                  name: item.name,
                  sn: item.sn,
                  price: item.price,
                  quantity: item.quantity,
                  spec: item.spec,
                  cost: item.cost,
                  unit:item.unit
                };
                itemList.push(goodsDetails)
              }
            });
            let formData = {
              id:_this.form.id,
              orderDate: _this.form.orderDate,
              outShopId:this.form.outShopId,
              inShopId:this.form.inShopId,
              officeId: _this.form.officeId,
              memo: _this.form.memo,
              itemList: itemList
            };
            update(formData).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('allocate-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/allocate/view', query: {id: _this.form.id}
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },

      selectSysEmployee(data) {
        this.form.operatorId = data
      },
      //  销售公司
      dialogShow() {
        console.log('点击了')
        this.$refs.officeDialog.show()
      },
      dialogConfirm(val) {
        this.form.officeId = val.id;
        this.officeName = val.name
      },

      //刷新商品合计
      refreshClick() {
        this.procuctFilter()

      },
      queryClick() {
        console.log('1111')
        var _this = this
        let params = new URLSearchParams();
        params.append('sn', _this.query.sn);
        findBySn(params).then(response => {
          console.log(response)
          if (response.data.products.length == 1){
            var goodsDetails = {
              productId: response.data.products[0].id,
              name: response.data.products[0].name,
              sn: response.data.products[0].sn,
              cost: response.data.products[0].cost,
              price: response.data.products[0].price,
              orders: response.data.products[0].orders,
              subTotal: response.data.products[0].price,
              unit:response.data.products[0].unit,
              spec:response.data.products[0].spec1 + response.data.products[0].spec2,
              amountPaid: 0,
              discount: 0,
              quantity: 1
            };
            _this.productList.push(goodsDetails)
            _this.procuctFilter()
          }else if (response.data.products.length > 1) {
            _this.findByList = response.data.products
            _this.queryType = true
          }
          _this.addProduct()
        }).catch(error => {
          console.log('error!!')
        });
      },
      queryClose(){
        this.queryType = false
      },
      findByClick(data) {
        var _this = this
        console.log(data)
        data.forEach(function (item) {
          _this.productList.push(item)
        });
        this.queryType = false
        this.procuctFilter();
      },
      toCalculateClick(){
        var _this = this
        _this.form.amountPayable = parseFloat(_this.form.subPrice) + parseFloat(_this.form.freight) -  parseFloat(_this.form.offsetAmount) ;
      }
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }
  .elOption1{
    background-color: #409EFF;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
  .elOption{
    background-color: #909399;
    color:white ;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 25%;
    height: 40px
  }
  .product_header_name {
    width: 100%;
    padding-right: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }
</style>
